package com.cloud.mybatis.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
import com.cloud.core.entity.permit.UserDeptRoleScope;
import lombok.SneakyThrows;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.Parenthesis;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;

import java.util.LinkedHashMap;

public class MyMultiDataPermissionHandler implements MultiDataPermissionHandler {
    @SneakyThrows
    @Override
    public Expression getSqlSegment(Table table, Expression where, String mappedStatementId) {
       /* LinkedHashMap<String,Object> permit = LoginHolder.getRoleScope();
        if(ObjectUtil.isEmpty(permit)){
            return null;
        }
        if (permit.get("dataScope").equals("1")) {
            return null;
        }
        if (LoginHolder.mapperFunSet.contains(mappedStatementId)) {
            if (permit.get("dataScope").equals("2")) {
                Expression expression = CCJSqlParserUtil.parseExpression("permit.dept_id = " + permit.get("dataScope"));
                Expression expression2 = CCJSqlParserUtil.parseExpression("find_in_set("+permit.get("dataScope")+" ,permit.ancestors  ) ");

                Parenthesis parenthesis = new Parenthesis(new OrExpression(expression, expression2));
                return new AndExpression(where, parenthesis);
            }
            if (permit.get("dataScope").equals("3")) {
                Expression expression = CCJSqlParserUtil.parseExpression("permit.dept_id = " + permit.get("dataScope"));
                Parenthesis parenthesis = new Parenthesis(expression);
                return new AndExpression(where, parenthesis);
            }
            if (permit.get("dataScope").equals("4")) {
                StringBuffer sb = new StringBuffer();
                sb.append("(");
          *//*      for(int i =0;i < permit.get("permits").size(); i++  ){
                    if(i==permit.getPermits().size()-1){
                        sb.append(permit.getPermits().get(i));
                    }else{
                        sb.append(permit.getPermits().get(i)+",");
                    }
                   sb.append(")");
                }*//*
                Expression expression = CCJSqlParserUtil.parseExpression("permit.dept_id in " + sb.toString());
                Parenthesis parenthesis = new Parenthesis(expression );
                return new AndExpression(where, parenthesis);
            }

        }*/


        return null;
    }
}
